package dragon.core.io;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileDigest {

	private static final Logger logger = LoggerFactory.getLogger(FileDigest.class);

	static MessageDigest md = null;

	static {
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException ne) {
		}
	}

	/**
	 * 对一个文件求他的md5值
	 * 
	 * @param filePath
	 *            要求md5摘要信息的文件路径
	 * @return md5串（大写）
	 */

	public static String md5Digest(String filePath) {

		File f = new File(filePath);
		if (!f.exists()) {
			return null;
		}
		BufferedInputStream bis = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(f));
			byte[] buffer = new byte[8192];
			int len = -1;
			while ((len = bis.read(buffer)) != -1) {
				md.update(buffer, 0, len);
			}
			return new String(Hex.encodeHex(md.digest())).toUpperCase();
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
			return null;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return null;
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}

	}

	public static void main(String[] args) {
		String md5 = md5Digest("C:\\Documents and Settings\\Administrator\\桌面\\fts\\b\\loginbg.jpg");
		System.out.println(md5);
	}

}
